import { IpcMain, IpcMainInvokeEvent } from 'electron'
import { Singleton } from '../factory/singleton'

/**
 * 可以在ipcMain上绑定方法的业务类
 */
export default class BaseService<T> extends Singleton<T> {
  protected constructor() {
    super()
  }

  /**
   * 处理 IpcMainHandle 装饰器装饰的方法
   * @param ipcMain
   */
  initIpcMainHandle(ipcMain: IpcMain) {
    const prototype = Object.getPrototypeOf(this)
    const propertyNames = Object.getOwnPropertyNames(prototype)
    propertyNames.forEach((method) => {
      const descriptor = Object.getOwnPropertyDescriptor(prototype, method)
      if (descriptor && descriptor.value && descriptor.value.__decorated) {
        ipcMain.handle(
          descriptor.value().methodName,
          async (event: IpcMainInvokeEvent, ...args: any[]) => {
            return descriptor.value().originalMethod(...args)
          }
        )
      }
    })
  }
}
